package com.sky.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sky.context.BaseContext;
import com.sky.po.AddressBookPO;
import com.sky.repository.AddressBookRepository;
import com.sky.service.AddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Slf4j
public class AddressBookServiceImpl implements AddressBookService {
    @Autowired
    private AddressBookRepository addressBookRepository;

    /**
     * 查询当前登录用户的所有地址或默认地址信息
     *
     * @param currentId
     * @return
     */
    public List<AddressBookPO> list(Long currentId, Boolean isDefault) {
        if(isDefault){
            return addressBookRepository.selectList(new LambdaQueryWrapper<AddressBookPO>()
                    .eq(AddressBookPO::getUserId,currentId)
                    .eq(AddressBookPO::getIsDefault, 1));
        }
        return addressBookRepository.selectList(new LambdaQueryWrapper<AddressBookPO>()
                .eq(AddressBookPO::getUserId,currentId));
    }

    /**
     * 新增地址
     *
     * @param addressBook
     */
    public void save(AddressBookPO addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBook.setIsDefault(0);
        addressBookRepository.insert(addressBook);
    }

    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    public AddressBookPO getById(Long id) {
        return addressBookRepository.selectById(id);
    }

    /**
     * 根据id修改地址
     *
     * @param addressBook
     */
    public void update(AddressBookPO addressBook) {
        addressBookRepository.updateById(addressBook);
    }

    /**
     * 设置默认地址
     *
     * @param addressBook
     */
    @Transactional
    public void setDefault(AddressBookPO addressBook) {
        //1、将当前用户的所有地址修改为非默认地址 update address_book set is_default = ? where user_id = ?
        addressBook.setIsDefault(0);
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBookRepository.updateIsDefaultByUserId(addressBook);

        //2、将当前地址改为默认地址 update address_book set is_default = ? where id = ?
        addressBook.setIsDefault(1);
        addressBookRepository.updateById(addressBook);
    }

    @Override
    public void deleteById(Long id) {
        addressBookRepository.deleteById(id);
    }


}
